package vip.hamlin.dnspod.task;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.StringUtils;
import vip.hamlin.dnspod.bean.*;
import vip.hamlin.dnspod.utils.HttpUtils;
import vip.hamlin.dnspod.utils.Utils;
import vip.hamlin.dnspod.utils.ValidateUtils;

import java.io.IOException;
import java.util.List;

/**
 * 更新dns记录的ip
 * Created by SunShao on 2016/6/1.
 */
@Configuration
@EnableAsync
@EnableScheduling
@SuppressWarnings("SpringJavaAutowiringInspection")
public class UpdateDNSTask {
    @Autowired
    private DNSPodRequestCommonParam dnsPodRequestCommonParam;

    @Autowired
    private DNSPodRecordListRequest dnsPodRecordList;

    @Autowired
    private DNSPodUpdateRecordRequest dnsPodUpdateRecordRequest;

    @Scheduled(cron = "${cron_expression}")
    public void updateDns() throws IOException {
        // 获取当前ip
        String currentIp = getCurrentIP();
        if (!StringUtils.isEmpty(currentIp)) {
            System.out.println(Utils.getCurrentTime() + " current ip is : " + currentIp);
            // 请求dnsPod获取需要更新的记录
            DNSPodRecordListResponse.Records needUpdateRecord = getRecordForNeedUpdateSubDomain();
            // 更新记录ip
            updateRecord(currentIp, needUpdateRecord);
        } else {
            System.out.println(Utils.getCurrentTime() + " get current ip failed!");
        }
    }

    private void updateRecord(String currentIp, DNSPodRecordListResponse.Records needUpdateRecord) {
        if (needUpdateRecord != null) {
            // 对比currentIP和value
            if (currentIp.equalsIgnoreCase(needUpdateRecord.getValue())) {
                System.out.println(Utils.getCurrentTime() + " current ip and needUpdateRecord ip no difference");
            } else {
                // 设置updata请求的2个必填参数record_id&value
                dnsPodUpdateRecordRequest.setRecord_id(needUpdateRecord.getId());
                dnsPodUpdateRecordRequest.setValue(currentIp);
                dnsPodUpdateRecordRequest.setRecord_line(needUpdateRecord.getLine());
                updateRecord();
            }
        } else {
            System.out.println(Utils.getCurrentTime() + " get need update needUpdateRecord failed!");
        }
    }

    private DNSPodRecordListResponse.Records getRecordForNeedUpdateSubDomain() {
        boolean isFindSubDomain = false;
        DNSPodRecordListResponse response = getRecordList();
        if (response != null) {
            List<DNSPodRecordListResponse.Records> records = response.getRecords();
            if (records != null) {
                // 取出指定子域名当前dnspod记录的ip
                for (DNSPodRecordListResponse.Records record : records) {
                    if (record.getName().equalsIgnoreCase(dnsPodUpdateRecordRequest.getSub_domain())) {
                        isFindSubDomain = true;
                        System.out.println(Utils.getCurrentTime() + " current dnspod record ip is : " + record.getValue());
                        return record;
                    }
                }
            } else {
                System.out.println(Utils.getCurrentTime() + " get record list failed!");
            }
        } else {
            System.out.println(Utils.getCurrentTime() + " request record list failed!");
        }
        if (!isFindSubDomain) {
            System.out.println("没有找到需要更新的子域名！请检查dnspod_update_record_config.properties文件中sub_domain参数配置是否正确！");
        }
        return null;
    }

    private void updateRecord() {
        String url = dnsPodRequestCommonParam.getDnspodHttpsUrl() + dnsPodUpdateRecordRequest.getUpdate_record_path();
        String result = HttpUtils.doPost(url, dnsPodRequestCommonParam.toString() + "&" + dnsPodUpdateRecordRequest.toString());
        DNSPodUpdateRecordResponse response = JSON.parseObject(result, DNSPodUpdateRecordResponse.class);
        System.out.println(Utils.getCurrentTime() + response.getStatus().getMessage());

    }

    private DNSPodRecordListResponse getRecordList() {
        String resultJson = HttpUtils.doPost(dnsPodRequestCommonParam.getDnspodHttpsUrl() + dnsPodRecordList.getRecordList(), dnsPodRequestCommonParam.toString() + "&" + dnsPodRecordList.toString());
        if (StringUtils.isEmpty(resultJson))
            return null;
        return JSON.parseObject(resultJson, DNSPodRecordListResponse.class);
    }


    private String getCurrentIP() {
        String result = HttpUtils.doGet(dnsPodRequestCommonParam.getCurrentIPURL());
        if (!ValidateUtils.isIp(result)) {
            return null;
        }
        return result;
    }

}
